package alijk.dataView.utils;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import alijk.dataView.model.RequestBean;
import alijk.dataView.model.ResponseBean;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

public class JAXBDemo {
	
	public static void main(String[] args) throws JAXBException, MalformedURLException {
		JAXBContext jc = JAXBContext.newInstance(RequestBean.class);
		
		Unmarshaller u = jc.createUnmarshaller();
		String xml = "<xml><ToUserName><![CDATA[gh_217ace14c180]]></ToUserName><FromUserName><![CDATA[ogBAIjybHILFTBCC_Ug8b1teFiYI]]></FromUserName><CreateTime>1358172380</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[天堂]]></Content><MsgId>5833305954430917613</MsgId></xml>";
		RequestBean reqBean = (RequestBean) u.unmarshal(new StringReader(xml));
		System.out.println(reqBean.getContent());
		System.out.println(reqBean.getCreateTime());
		
		System.out.println("-------------------------");
		
		jc = JAXBContext.newInstance(ResponseBean.class);
		Marshaller m = jc.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		m.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
			
			@Override
			public void escape(char[] arg0, int arg1, int arg2, boolean arg3,
					Writer arg4) throws IOException {
				arg4.write(arg0, arg1, arg2);
			}
		});
		m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
		ResponseBean respBean = new ResponseBean();
		respBean.setFromUserName(reqBean.getToUserName());
		respBean.setToUserName(reqBean.getFromUserName());
		respBean.setMsgType("text");
		respBean.setCreateTime(new Date().getTime());
		respBean.setContent("地狱");
		StringWriter ws = new StringWriter();
		m.marshal(respBean, ws);
		System.out.println(ws.toString());
		
	}
}
